<?php
/**
 * 大客户信息 ajax类
 * @package  ajax
 * @subpackage  backend
 * @author   create by allen.qiang
 */

quanli_require('module/base/company/companyMaster.class.php');

//用户类
quanli_require('module/base/system/sysUser.class.php');

//部门类
quanli_require('module/base/system/sysDepartment.class.php');

class ajax_company{

    public function execute() {

        if(isset($_REQUEST['operFlg']) && quanli_is_int($_REQUEST['operFlg'])){

            switch($_REQUEST['operFlg']){

                case 1://大客户列表
                    $properties = isset($_REQUEST['properties']) ? $_REQUEST['properties'] : null;
                    $this->companyList($properties);
                    break;

                case 2://查询销售人员
                    $this->searchSaler();
                    break;

                case 3://直接转为老客户
                    $this->checkCompany();
                    break;

                case 4://查看客户拜访记录
                    $this->companyRecord();
                    break;

                case 5://保存拜访记录
                    $this->saveRecord();
                    break;

                case 100:

                    if (!isset($_REQUEST['act']) || !in_array($_REQUEST['act'], array('del', 'edit', 'change','search'))) {
                        returnJsonData('参数错误');
                    }

                    if ($_REQUEST['act'] == 'edit') {

                        $this->edit();//新增、修改 大客户信息

                    } else if ($_REQUEST['act'] == 'del') {

                        $this->deleteCompany();//删除大客户信息

                    } else if ($_REQUEST['act'] == 'change') {

                        $this->changeCompany(); //大客户信息启用/禁用
                    //公司名称模糊查询 add loreta.cheng 2015-06-10 start
                    }else if ($_REQUEST['act'] == 'search') {

                        $this->searchCompany(); //模糊查询公司名称

                    }
                    //公司名称模糊查询 add loreta.cheng 2015-06-10 end
                    break;

                default:

                    returnJsonData('参数错误');

                    break;
            }

        }else {
            returnJsonData('参数错误');
        }
    }

    /**
     * 大客户列表
     */
    private function companyList($properties){

        global $G_SHOP;

        //获得用户的所属部门及以下部门
        $PS_LOGIN_SESSION =$G_SHOP->sessionCache_get('PS_LOGIN_SESSION');
        $departmentID = $PS_LOGIN_SESSION['department'];//当前部门id

        //实例化部门类
        $sysDepartment = new sysDepartment();

        //部门数据
        $department_array = array();
        //递归查询部门数据
        $sysDepartment->searchDepartment( $department_array,0,-1,$departmentID);

        //递归获得多维数组索引的方法（部门id）的方法
        function getKey( $array , &$foreachKey_array){

            if( is_array( $array ) ){
                foreach( $array as $k=>$v){
                    if( $k == "departmentID"){
                        $foreachKey_array[] = $v;
                    }

                    if( is_array( $v )){
                        getKey( $v, $foreachKey_array );
                    }
                }
            }
        }

        $departmentKeyArray = array();
        getKey( $department_array, $departmentKeyArray );
        if( !empty($departmentKeyArray) ) { //当前登录用户权限下部门
            $str_departmentID = implode( ',',$departmentKeyArray );
            $_REQUEST['extend'] = " AND departmentID IN (".$str_departmentID.")";
        } else { //当前登录用户没有任何所属部门
            //组织返回的数据
            $result_array = array(
                'page' => 1,
                'total' => 0,
                'rows' => array()
            );
            echo json_encode($result_array);
        }

        //实例化大客户信息类
        $companyMaster = new companyMaster();
        if( isset( $_REQUEST['search_departmentID'] )){
           // $_REQUEST['departmentID'] = $_REQUEST['search_departmentID'];

            if($_REQUEST['search_departmentID']!=""){

                $department_arrays = array();
                //实例化部门类
                $sysDepartments = new sysDepartment();
                //递归查询部门数据
                $sysDepartments->searchDepartment( $department_arrays,0,-1,$_REQUEST['search_departmentID']);
                $departmentKeyArrays= array();
                getKey( $department_arrays, $departmentKeyArrays );
                $str_departmentIDs = implode( ',',$departmentKeyArrays );

                $_REQUEST['departmentID'] =$str_departmentIDs;

            }else{
                $_REQUEST['departmentID'] = $_REQUEST['search_departmentID'];
            }

        }
        $_REQUEST['properties']=$properties;
        $arg_array = $_REQUEST;
        $result = $companyMaster->search( $arg_array );
        //组织返回的数据
        $result_array = array(
            'page' => $arg_array['page'],
            'total' => $arg_array['count'],
            'rows' => array()
        );
        //大客户和申领单添加公司名称列表分页bug修改 add by loreta.cheng 2015-06-11 start 
        if (isset($_REQUEST['list_type']) && $_REQUEST['list_type'] == 'general' && $_REQUEST['show_type'] && $_REQUEST['way_type']) {

            $result_array['data'] = $result;
            $result_array['company_name'] = $_REQUEST['company_name'];
            if ($result) {
                $result_array['paging'] = shop_page($arg_array['page'], $arg_array['count'], $arg_array['rp'], 'javascript: '.$_REQUEST['show_type'].'.'.$_REQUEST['way_type'].'(%d);', $G_SHOP->smarty, 'comm/page.tpl');
            }
        //add by loreta.cheng 2015-06-11 end
        } else {

            if ($result) {

                $edit_permission = $G_SHOP->has_permission(60001);

                foreach($result as &$data) {

                    if ($edit_permission) {

                        $operation_html = '';
                        $operation_html .= '<a href="javascript:void(0);" onclick="company.edit.open(' . $data['company_id']. ',' . $data['properties']  . ');">修改</a>&nbsp;&nbsp;';
                        $operation_html .= '<a href="javascript:openCost(' . $data['company_id']. ');" >报价单</a>&nbsp;&nbsp;';
                        $operation_html .= '<a href="javascript:openRecord(' . $data['company_id']. ');" >拜访记录</a>&nbsp;&nbsp;';

                        $use_html = '';
                        if (isset($data['useFlg']) && $data['useFlg'] == 1) {
                            $use_html .= '<a href="javascript:void(0);" onclick="company.change.check(' . $data['company_id'] . ', ' . $data['useFlg'] . ');">启用</a>';
                        } else {
                            $use_html .= '<a href="javascript:void(0);" onclick="company.change.check(' . $data['company_id'] . ', ' . $data['useFlg'] . ');">禁用</a>';
                        }
//                        $properties_html="老客户";
//                        if (isset($data['properties']) && $data['properties'] == 1) {
//                            $operation_html="";
//                            $properties_html="驳回";
//                        } else if (isset($data['properties']) && $data['properties'] == 0){
//                            $properties_html="新客户";


                            //转为老客户
//                            if($G_SHOP->has_permission(60003)){
//                                $operation_html .= '&nbsp;&nbsp;<a href="javascript:void(0);" onclick="company.check(' . $data['company_id']. ');">转为老客户</a>';
//                            }

//                        }

                        $result_array['rows'][] = array (
                            'id' => $data['company_id'],
                            'cell' => array(
                                $operation_html,
                                //$properties_html,
                                $data['company_name'],
                                $data['connect_name'],
                                $data['address'],
                                $data['mobile'],
                                //$data['phone'],
                                //$data['website'],
                                //$data['employees_number'],
                                //$data['industry'],
                                //$data['nature'],
                                $data['departmentName'],
                                $data['userName'],
                                $data['note'],
                                $use_html
                            )
                        );

                    } else {

                        $operation_html = '';
                        $result_array['rows'][] = array (
                            'id' => $data['company_id'],
                            'cell' => array(
                                $operation_html,
                                //$data['properties'],
                                $data['company_name'],
                                $data['connect_name'],
                                $data['address'],
                                $data['mobile'],
                                //$data['phone'],
                                //$data['website'],
                                //$data['employees_number'],
                                //$data['industry'],
                                //$data['nature'],
                                $data['departmentName'],
                                $data['userName'],
                                $data['note'],
                                $data['useFlg'] == 1 ? '启用' : '禁用',
                            )
                        );

                    }

                }

            }

        }

        echo json_encode($result_array);

    }

    /**
     * 新增/修改地址
     */
    private function edit() {

        global $G_SHOP;

        //实例大客户信息
        $companyMaster = new companyMaster();

        $_REQUEST['creator'] = $G_SHOP->currentUserID;
        $result_array = $companyMaster->editCompany( $_REQUEST );

        returnJsonData($result_array['message'], $result_array['code']);

    }

    /**
     * 大客户信息启用/禁用
     */
    private function changeCompany () {

        //实例大客户信息类
        $companyMaster = new companyMaster();

        //大客户信息启用/禁用
        $result_array = $companyMaster->changeCompanyUseflg( $_REQUEST );

        returnJsonData( $result_array['message'], $result_array['code'] );

    }

    /**
     * 删除大客户信息
     */
    private function deleteCompany () {

        //实例大客户信息类
        $companyMaster = new companyMaster();

        //批量删除大客户信息
        $result_array = $companyMaster->deleteCompany( $_REQUEST['p_array'] );

        returnJsonData( $result_array['message'], $result_array['code'] );

    }

    /**
     * 查询销售人员
     */
    private function searchSaler () {


        global $G_SHOP;

        $sysUser = new sysUser($G_SHOP->DBCA);//实例用户类

        if( isset($_REQUEST['departmentID']) && !is_numeric( $_REQUEST['departmentID'] )){
            returnJsonData('参数错误',404);
        }

        //实例化部门类
        $sysDepartment = new sysDepartment();

        //部门数据
        $department_array = array();
        //递归查询部门数据
        $sysDepartment->searchDepartment( $department_array,0,-1,$_REQUEST['departmentID']);

        //递归获得多维数组（部门id）的方法
        function getKey( $array , &$foreachKey_array){

            if( is_array( $array )){
                foreach( $array as $k=>$v){
                    if( $k == "departmentID"){
                        $foreachKey_array[] = $v;
                    }

                    if( is_array( $v )){
                        getKey( $v, $foreachKey_array );
                    }
                }
            }
        }


        $departmentKeyArray = array();

        getKey( $department_array, $departmentKeyArray );


        if( $departmentKeyArray ){ //当前登录用户权限下部门
            $str_departmentID = implode( ',',$departmentKeyArray );
            $_REQUEST['extend'] = " AND departmentID IN (".$str_departmentID.")";
        }

        $arg_array = array(
            'useFlg' => 1,
            'isSalesman' => 1,
            'extend'=>$_REQUEST['extend']
        );


        $user_array = $sysUser->searchUserInfo( $arg_array );

        returnJsonData( 'ok', 200, $user_array );

    }


    /*
     * 直接转为大客户
     */
    private function checkCompany(){

        global $G_SHOP;

       $company = new entity('company_master');
       $company ->company_id=$_REQUEST['companyID'];
       $G_SHOP->DBCA->fetch($company);
       $company ->properties= 2;
        $result_array= $G_SHOP->DBCA->save($company);
        if($result_array==1){
            die(json_encode(array('code' => 200, 'message' => '转为老客户成功')));
        }else{
            die(json_encode(array('code' => 400, 'message' => '转为老客户失败')));
        }
    }
    /*
     * 公司名称模糊查询
     * @auther allen.qiang@fistforward.com
     */
     private function searchCompany(){

        //实例大客户信息类
        $companyMaster = new companyMaster();

        //大客户公司名称模糊查询
        $result_array = $companyMaster->search( $_REQUEST );
        if(is_array($result_array)){
          returnJsonData( 'ok', 200, $result_array);
        }else{
          returnJsonData( '没有你要查询的公司信息', 400, $result_array);
        }

     }

     //拜访记录
     private function companyRecord()
     {
         global $G_SHOP;

         //获得用户的所属部门及以下部门
         $PS_LOGIN_SESSION =$G_SHOP->sessionCache_get('PS_LOGIN_SESSION');
         $departmentID = $PS_LOGIN_SESSION['department'];//当前部门id

         //实例化部门类
         $sysDepartment = new sysDepartment();

         //部门数据
         $department_array = array();
         //递归查询部门数据
         $sysDepartment->searchDepartment( $department_array,0,-1,$departmentID);

         //递归获得多维数组索引的方法（部门id）的方法
         function getKey( $array , &$foreachKey_array){

             if( is_array( $array )){
                 foreach( $array as $k=>$v){
                     if( $k == "departmentID"){
                         $foreachKey_array[] = $v;
                     }

                     if( is_array( $v )){
                         getKey( $v, $foreachKey_array );
                     }
                 }
             }
         }


         $departmentKeyArray = array();
         getKey( $department_array, $departmentKeyArray );

         if( !empty($departmentKeyArray) ) { //当前登录用户权限下部门
             $str_departmentID = implode( ',',$departmentKeyArray );
             $_REQUEST['extend'] = " AND cm.departmentID IN (".$str_departmentID.")";
         } else { //当前登录用户没有任何所属部门
             //组织返回的数据
             $result_array = array(
                 'page' => 1,
                 'total' => 0,
                 'rows' => array()
             );
             echo json_encode($result_array);
         }

         //实例化大客户信息类
         $companyMaster = new companyMaster();
         if( isset( $_REQUEST['search_departmentID'] )){
             if($_REQUEST['search_departmentID']!=""){
                 $department_arrays = array();
                 //实例化部门类
                 $sysDepartments = new sysDepartment();
                 //递归查询部门数据
                 $sysDepartments->searchDepartment( $department_arrays,0,-1,$_REQUEST['search_departmentID']);
                 $departmentKeyArrays= array();
                 getKey( $department_arrays, $departmentKeyArrays );
                 $str_departmentIDs = implode( ',',$departmentKeyArrays );
                 $_REQUEST['departmentID'] =$str_departmentIDs;
             }else{
                 $_REQUEST['departmentID'] = $_REQUEST['search_departmentID'];
             }
         }

         $arg_array = $_REQUEST;
         $result = $companyMaster->searchRecord( $arg_array );
         //组织返回的数据
         $result_array = array(
             'page' => $arg_array['page'],
             'total' => $arg_array['count'],
             'rows' => array()
         );

         if ($result) {
             foreach($result as $data) {
                 $result_array['rows'][] = array (
                     'id' => $data->recordId,
                     'cell' => array(
                         $data->company_name,
                         $data->trueName,
                         $data->recordDate,
                         $data->contacts,
                         $data->mobile,
                         $data->address,
                         $data->content,
                         $data->feedback,
                         $data->opinion,
                     )
                 );
             }
         }
         echo json_encode($result_array);
     }

     //保存拜访记录
     public function saveRecord()
     {
         global $G_SHOP;

         $arg_array = $_REQUEST;
         if (!isset($arg_array['company']) || empty($arg_array['company'])) {
             returnJsonData('请选择客户');
         }
         if (!isset($arg_array['contacts']) || empty($arg_array['contacts'])) {
             returnJsonData('请填写联系人');
         }
         if (!isset($arg_array['mobile']) || empty($arg_array['mobile'])) {
             returnJsonData('请填写联系电话');
         }
         if (!isset($arg_array['recordDate']) || empty($arg_array['recordDate'])) {
             returnJsonData('请选择拜访时间');
         }
         if (!isset($arg_array['address']) || empty($arg_array['address'])) {
             returnJsonData('请填写拜访地址');
         }
         if (!isset($arg_array['content']) || empty($arg_array['content'])) {
             returnJsonData('请填写拜访内容');
         }

         $companyMaster = new companyMaster();
         $arg_array['creator'] = $G_SHOP->currentUserID;
         $result = $companyMaster->saveRecord($arg_array);
         if ($result['code'] == 200) {
             returnJsonData('保存成功', 200);
         }
         returnJsonData('保存失败');
     }
}
